<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2022/1/20
 * Time: 10:28 上午
 */

namespace app\api\controller\v30;

use app\api\controller\v2\Auth;
use app\chat\LiveMessage;
use app\chat\LiveMessage as CharLiveMessage;
use app\common\cachemodel\live\LiveAnchorInfo;
use app\common\cachemodel\live\LiveAnswerAstroRecord;
use app\common\cachemodel\live\LiveAnswerDiceRecord;
use app\common\cachemodel\live\LiveAnswerReward;
use app\common\cachemodel\live\LiveAnswerScore;
use app\common\cachemodel\live\LiveAnswerTarotRecord;
use app\common\cachemodel\live\LiveOrderData;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZlTarotRecords;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Divination;
use app\common\model\MessageCenter;
use app\common\model\Recode;
use think\response\Json;

/**
 * Class LiveAnswerInfo
 * @package app\api\controller\v30
 */
class LiveUserAnswerInfo extends Auth
{
    /**
     * 星盘解答申请
     */
    public function requestAstroAnswer()
    {
        $liveRecordId = input('live_record_id/d', 0);
        $rid = input('rid/d', 0);
        $rid2 = input('rid2/d', 0);
        $question = trim(input('question/s', ''));
        $questionDes = trim(input('question_des/s', ''));
        $type = 1;  // 1单盘 2合盘
        $liveAnswerAstroModel = new LiveAnswerAstroRecord();
        if (!$rid)
        {
            return show(config('code.error'), '申请失败，请选择档案');
        }

        $recode = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        if (empty($recode))
        {
            return show(config('code.error'), '申请失败，档案信息异常');
        }

        if ($rid2)
        {
            $recode2 = (new Recode())->getRecode(['uid' => $this->user['id'], 'id' => $rid2]);
            if (empty($recode2))
            {
                return show(config('code.error'), '申请失败，档案信息异常');
            }
            $type = 2;
        }
        if (empty($question))
        {
            return show(config('code.error'), '看盘问题不能为空');
        }

        if (mb_strlen($question) > 42)
        {
            return show(config('code.error'), '看盘问题最多42字');
        }

        if (mb_strlen($questionDes) > 100)
        {
            return show(config('code.error'), '看盘问题描述最多100字');
        }

        $liveRecordingInfo = new LiveRecordingInfo();
        $liveRecordInfo = $liveRecordingInfo->getInfoById($liveRecordId);
        // 获取当前 申请连麦信息
        $liveAnchorInfoModel = new LiveAnchorInfo();
        $resConfig = $liveAnchorInfoModel->getAnswerConfig($liveRecordInfo['live_id'], $liveRecordId, 'astro');

        if ((int)$resConfig['switch'] !== 1)
        {
            return show(config('code.error'), '主播未开启申请看盘');
        }
        $resConfig['type'] = (int)$resConfig['type'];
        $userGroupName = '所有人';
        if ($resConfig['type'] === 1)
        {   // 免费情况
            $resConfig['people_auth'] = (int)$resConfig['people_auth'];
            if ($resConfig['people_auth'] === 2)
            {
                $userGroupName = '下单用户';
                // 下单权限验证  是否在本场直播中下单
                $orderUids = (new LiveOrderData())->getLiveRecordOrderUid($liveRecordId);
                if (!$orderUids || !in_array($this->user['id'], $orderUids, false))
                {   // 下单了的用户
                    return show(config('code.error'), '主播设置了权限，请稍后再试～');
                }
            } elseif ($resConfig['people_auth'] === 3)
            {
                $userGroupName = '会员用户';
                $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
                if ($vipLevel < 1)
                {   // 不是VIP 则返回
                    return show(config('code.error'), '主播设置了权限，请稍后再试～');
                }
            }
        }

        if ((int)$resConfig['is_allow_synastry'] !== 1 && $type === 2)
        {
            return show(config('code.error'), '申请看盘异常，请稍后再试～');
        }
        // 获取申请的所有人
        $answerList = $liveAnswerAstroModel->getRequestAnswerUserList($liveRecordInfo['live_id'], $liveRecordId, $resConfig['type']);
        // 判断申请人数是否已满
        if ($answerList)
        {
            $uids = array_keys($answerList);
            if (in_array($this->user['id'], $uids, false))
            {   // 已经申请过了  且 是申请成功
                return show(config('code.error'), '已经提交过申请了，不能再次申请～');
            }
        }
        $requestAnswerNum = count($answerList);    // 申请解答用户
        $isRequest = false;
        if ($resConfig['type'] === 2)
        {   // 付费
            // 当前有待支付订单 不允许再次申请
            $reqInfo = $liveAnswerAstroModel->getUserRequestAnswerPrepareInfo($liveRecordInfo['live_id'], $liveRecordId, $this->user['id']);
            if ($reqInfo && (int)$reqInfo['status'] === 1)
            {
                return show(config('code.error'), '已经提交过申请了，不能再次申请～');
            }

            $prepareUser = $liveAnswerAstroModel->getAnswerPrepareUser($liveRecordInfo['live_id']);
            if (in_array($this->user['id'], $prepareUser, false))
            {   //  已经占过位置
                $isRequest = true;
            } else
            {
                $requestAnswerNum = $requestAnswerNum + count($prepareUser);    // 加上 申请中用户
            }
        }

        if (!$isRequest && $requestAnswerNum >= $resConfig['max_people_num'])
        {
            return show(config('code.error'), '当前申请人数已满，请稍后再试～');
        }

        // 判断 看盘
        $answerInfo = [
            'uid' => (int)$this->user['id'],
            'live_id' => (int)$liveRecordInfo['live_id'],
            'live_record_id' => (int)$liveRecordId,
            'type' => $type,
            'rid' => $rid,
            'rid2' => $type === 2 ? $rid2 : 0,
            'question' => $question,
            'question_des' => $questionDes,
            'price' => $resConfig['type'] == 2 ? $resConfig['price'] : 0,
            'extend' => json_encode([
                'recode1' => $recode,
                'recode2' => $recode2 ?? null,
            ])
        ];

        if ($resConfig['type'] === 2)
        {   // 付费
            $answerInfo['status'] = 0;
            $answerInfo['sign'] = uniqid();
            $liveAnswerAstroModel->setUserRequestAnswerPrepareInfo($answerInfo['live_id'], $liveRecordId, $answerInfo['uid'], $answerInfo);
            // 占位
            $liveAnswerAstroModel->addAnswerPrepareUser($answerInfo['live_id'], $answerInfo['uid']);
            // 释放占位 延迟队列 =>未生成订单 则释放 已生成订单则不释放
            Util::queuePush('live_answer_down_order_timeout_check', [
                'sign' => $answerInfo['sign'],
                'live_id' => $answerInfo['live_id'],
                'live_record_id' => $answerInfo['live_record_id'],
                'uid' => $answerInfo['uid'],
                'type' => 1
            ], 120);

            $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);

            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache((int)$answerInfo['uid']);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $coinPwdStatus = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码

            //  直播解答问题提交成功 LiveQuestionAdd 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionAdd', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'price' => $resConfig['price'],   //  价格
                'users_group' => '无',
                'question_type' => '看盘',   // 解答类型
                'question' => $question,    // 问题的具体内容
                'description' => $questionDes, // 问题的描述
            ]);

            return show(config('code.success'), '请求成功', [
                'live_name' => $liveInfo['name'],
                'good_img' => '/live/answer/astro_icon2.png',
                'good_name' => '直播看盘解答',
                'price' => $resConfig['price'],
                'coin' => $coinNum,
                'is_set_password' => $coinPwdStatus,
            ]);
        } else
        {   // 免费
            $id = $liveAnswerAstroModel->addAnswerRequest($answerInfo);

            $nowData = $liveAnswerAstroModel->getNowAnswerDataByCache($liveRecordId);

            if ($nowData && (int)$nowData['status'] === 5)
            {
                $name = $nowData['nickname'];
                $avatar = $nowData['avatar'];
            }

            $recodeList[] = [
                'id' => $recode['id'],
                'name' => $recode['name'],
                'type' => $recode['type'] == 1 ? 1 : 2,
                'age' => '年龄' . birthday($recode['year'] . '-' . $recode['month'] . '-' . $recode['day']),
                'comments' => $recode['comments']
            ];
            if (isset($recode2))
            {
                $recodeList[] = [
                    'id' => $recode2['id'],
                    'name' => $recode2['name'],
                    'type' => $recode2['type'] == 1 ? 1 : 2,
                    'age' => '年龄' . birthday($recode2['year'] . '-' . $recode2['month'] . '-' . $recode2['day']),
                    'comments' => $recode2['comments']
                ];
            }


            $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);
            //  直播解答问题提交成功 LiveQuestionAdd 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionAdd', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'price' => 0,   //  价格
                'users_group' => $userGroupName,
                'question_type' => '看盘',   // 解答类型
                'question' => $question,    // 问题的具体内容
                'description' => $questionDes, // 问题的描述
            ]);
            //  直播解答申请成功    LiveQuestionApplySuccess    打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionApplySuccess', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'is_synastry' => $type === 2, // 是否合盘 bool  type=>1单盘 2合盘
                'question_type' => '看盘',   // 解答类型
                'price' => 0,   //  价格
                'question' => $question,    // 问题的具体内容
                'description' => $questionDes, // 问题的描述
            ]);

            if ($nowData)
            {
                $liveWsData = [
                    'icon' => "/live/answer/astro_icon.png",
                    'hint' => (int)$nowData['status'] === 5 ? '解答中' : '待响应',
                    'type' => 1,
                    'status' => 1,
                    'id' => $id
                ];
            } else
            {
                $liveWsData = [
                    'icon' => "/live/answer/astro_icon.png",
                    'hint' => '未开始',
                    'type' => 1,
                    'status' => 1,
                    'id' => 0
                ];
            }
            // 图标显隐消息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, $liveWsData);

            return show(config('code.success'), '请求成功', [
                'id' => (int)$id,
                'status' => 12,
                'title' => '已成功申请看盘，请等待主播讲解…',
                'des' => '请不要离开直播间，主播会在直播间内为你解答问题',
                'name' => $name ?? '',
                'avatar' => $avatar ?? '',
                'wait_tips' => '当前' . ($requestAnswerNum + 1) . '人等待…',
                'question' => $question,
                'question_des' => $questionDes,
                'recode_list' => $recodeList,
            ]);
        }
    }

    /**
     * 更新看盘申请
     * @return Json
     * @throws \Exception
     */
    public function alterRequestAstroAnswer()
    {
        $id = input('id/d', 0);
        $question = trim(input('question/s', ''));
        $questionDes = trim(input('question_des/s', ''));

        $history = (new LiveAnswerAstroRecord())->getInfoById($id, ['uid', 'status', 'price']);
        if (!$history || $history['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '申请不存在');
        }

        // 更新解答状态
        (new LiveAnswerAstroRecord())->updateAnswerRequest([
            'id' => $id,
            'question' => $question,
            'question_des' => $questionDes,
        ]);

        //状态  1=>待支付 2=>等待解答｜排队中  3=>待响应 4=>未响应 5=>解答中 6=>解答完成 7=>订单关闭取消(待支付状态取消) 8=>用户主动取消 9=>主播取消 10=>未响应3次后取消（支付成功后）
        switch ($history['status'])
        {
            case 1:
            case 4:
                $status = 21;
                break;
            case 2:
                if ($history['price'] > 0)
                {
                    $status = 22;
                } else
                {
                    $status = 12;
                }
                break;
            case 3:
                $status = 24;
                break;
            case 5:
                if ($history['price'] > 0)
                {
                    $status = 25;
                } else
                {
                    $status = 15;
                }
                break;
            default:
                $status = 0;
                break;
        }
        return show(config('code.success'), '更新成功', ['status' => $status]);

    }

    /**
     * 修改解答状态
     */
    public function alterAnswerStatus()
    {
        $id = input('id/d', 0);  // 申请记录ID
        $status = input('status/d', 0); // 1=>接受解答，2=>等一会，3=>取消申请
        $reasonId = input('reason_id/d', 0);    // 取消原因
        $type = input('type/d', 0);    // 问题类型 1=>看盘，2=>骰子，3=>塔罗
        $liveRecordId = input('live_record_id/d', 0);

        if (!$id || !in_array($status, [1, 2, 3], true) || !in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        //验证申请是否存在
        $liveAnswerModel = null;
        $typeName = '';
        $needAuth = 0;
        $orderType = 0;
        $answerName = '';
        switch ($type)
        {
            case 1://看盘
                $liveAnswerModel = new LiveAnswerAstroRecord();
                $typeName = 'astro';
                $needAuth = 1;
                $answerName = '看盘';
                $orderType = 19;
                break;
            case 2:// 骰子
                $liveAnswerModel = new LiveAnswerDiceRecord();
                $typeName = 'dice';
                $needAuth = 2;
                $answerName = '骰子';
                $orderType = 20;
                break;
            case 3:// 塔罗
                $liveAnswerModel = new LiveAnswerTarotRecord();
                $typeName = 'tarot';
                $needAuth = 2;
                $answerName = '塔罗';
                $orderType = 21;
                break;
        }

        $answerInfo = $liveAnswerModel->getInfoById($id);

        if (!$answerInfo || (int)$answerInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，申请解答信息不存在～');
        }

        $answerInfo['status'] = (int)$answerInfo['status'];
        $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);
        switch ($status)
        {
            case 1:
                $nowAnswerData = $liveAnswerModel->getNowAnswerDataByCache($liveRecordId);
                if (!$nowAnswerData)
                {
                    return show(config('code.error'), '服务异常，操作失败～');
                }

                if ((int)$nowAnswerData['uid'] !== $this->user['id'])
                { //status  当前连麦状态 1=>邀请等待用户接受 2=>用户接受开始连麦中 3=>连麦成功 连麦中
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }

                if ((int)$nowAnswerData['status'] !== 3)
                {
                    return show(config('code.error'), '解答中，操作失败～');
                }

                // 更新解答状态
                $liveAnswerModel->updateAnswerRequest([
                    'id' => $id,
                    'status' => 5,
                    'start_time' => $this->request->time(),
                ]);

                $resStatus = $liveAnswerModel->saveNowAnswerDataToCache($liveRecordId, [
                    'status' => 5,  // 当前解答状态 状态  1=>待支付 2=>等待解答｜排队中  3=>待响应 4=>未响应 5=>解答中 6=>解答完成 7=>超时取消 8=>用户主动取消 9=>主播取消
                    'request_time' => $this->request->time(),   // 邀请用户解答时间
                ]);

                if (!$resStatus)
                {
                    return show(config('code.error'), '服务异常，解答失败');
                }

                // ws 消息
                // 管理员端
                // 图标显隐消息
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                    , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, [
                        'icon' => "/live/answer/{$typeName}_icon.png",
                        'hint' => '解答中',
                        'type' => $type,
                        'status' => 1,
                        'id' => $id
                    ]);
                // 向管理员 发送消息
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                    , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_RESPONSE_STATUS, [
                        'type' => $type,
                        'status' => 4,
                        'id' => $id
                    ]);

                $answerList = $liveAnswerModel->getRequestAnswerUserList($answerInfo['live_id'], $liveRecordId, 2);
                foreach ($answerList as $uid => $reqId)
                {
                    // 向直播间 申请用户 发送消息 发送更新详情消息
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, $answerInfo['live_id'], $uid)
                        , LiveMessage::MSG_TYPE_POP_ANSWER_REFRESH, [
                            'target' => 'local',
                            'link' => "live_{$typeName}?id={$reqId}&live_record_id={$liveRecordId}&need_auth={$needAuth}",
                            'type' => $type,
                            'force_open' => 0
                        ]);
                }

                return show(config('code.success'), '操作成功', [
                    'title' => '',
                    'des' => '',
                ]);
            case 2:
                $nowAnswerData = $liveAnswerModel->getNowAnswerDataByCache($liveRecordId);
                if (!$nowAnswerData || (int)$nowAnswerData['id'] !== $id || (int)$nowAnswerData['uid'] !== $this->user['id'])
                {
                    return show(config('code.error'), '服务异常，操作失败～');
                }

                if ((int)$nowAnswerData['status'] !== 3)
                {
                    return show(config('code.error'), '解答中，操作失败～');
                }

                // 等一会 删除当前解答中的缓存信息
                $liveAnswerModel->delNowAnswerDataByCache($liveRecordId);
                if ($answerInfo['price'] > 0)
                {   // 付费
                    $payType = 2;//付费
                } else
                {
                    $payType = 1;//免费
                }
                $answerList = $liveAnswerModel->getRequestAnswerUserList((int)$answerInfo['live_id'], $liveRecordId, $payType);

                if ($answerInfo['wait_num'] >= 2)
                {   // 稍等一会 次数达上线
                    // 更新订单并退款
                    $res = $liveAnswerModel->refundAnswerOrder(['id' => $answerInfo['id'], 'order_num' => $answerInfo['order_num'], 'status' => $answerInfo['status'], 'uid' => $answerInfo['uid'], 'wait_num' => $answerInfo['wait_num'] + 1,], $liveRecordId, 4, '');
                    if ($res === false)
                    {
                        return show(config('code.error'), '退款失败');
                    }
                    // 删除 排队信息
                    $liveAnswerModel->delRequestAnswerUserList((int)$answerInfo['live_id'], $liveRecordId, 2, (int)$answerInfo['uid']);
                    // 加入取消订单列表
                    $liveAnswerModel->addResAnswerUserList($liveRecordId, 2, [$answerInfo['id'] => $answerInfo['id']]);
                    $answerDelayStatus = 3;
                    unset($answerList[$answerInfo['uid']]);
                    // 消息中心添加信息
                    $messageData = [
                        'status' => 0,
                        'is_read' => 0,
                        'range' => $answerInfo['uid'],
                        'type' => 2,
                        'reid' => 0,
                        'cid' => 4,
                        'title' => '解答响应超时订单取消',
                        'content' => '非常抱歉，您的' . $answerName . '解答订单：' . $answerInfo['order_num'] . '因您响应超时被取消，您支付的资金将原路返还，请注意查收',// 消息中心跳转地址
                        'link' => "order_details?order_id={$answerInfo['order_num']}&order_type={$orderType}",
                        'target' => 'local',
                        'create_time' => time()
                    ];
                    (new MessageCenter())->pushMessage($answerInfo['uid'], $messageData);
                    // 发送推送
                    // (new Push())->pushUserMsg($answerInfo['uid'], '非常抱歉，您的' . $answerName . '解答订单：' . $answerInfo['order_num'] . '因您响应超时被取消，您支付的资金将原路返还，请注意查收', ['action' => 'extend', 'target' => 'local', 'link' => "order_details?order_id={$answerInfo['order_num']}&order_type={$orderType}"]);

                    //  直播取消订单成功 LiveQuestionCancle 打点
                    SensorsData::track($answerInfo['uid'], true, 'LiveQuestionCancle', [
                        'hoster_name' => $liveInfo['name'],    // 主播名称
                        'live_id' => $answerInfo['live_id'],    // 直播间ID
                        'live_record_id' => $liveRecordId,  // 直播记录ID
                        'price' => $answerInfo['price'] * 1,   //  价格
                        'cancle_reason' => '手动取消',
                        'question_type' => $answerName,   // 解答类型
                        'question' => $answerInfo['question'] ?? '',    // 问题的具体内容
                        'description' => $answerInfo['question_des'] ?? '无', // 问题的描述
                    ]);
                } else
                {
                    $answerDelayStatus = 1;
                    // 更新解答状态
                    // 更新解答状态
                    $liveAnswerModel->updateAnswerRequest([
                        'id' => $id,
                        'status' => 4,
                        'wait_num' => $answerInfo['wait_num'] + 1,
                    ]);
                }

                //  ws 消息
                // 当前用户发送通知
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, $answerInfo['live_id'], $this->user['id'])
                    , LiveMessage::MSG_TYPE_POP_ANSWER_REFRESH, [
                        'target' => 'local',
                        'link' => "live_{$typeName}?id={$id}&live_record_id={$liveRecordId}&need_auth={$needAuth}",
                        'type' => $type,
                        'force_open' => 1
                    ]);
                // 主播发送
                // 向管理员 发送消息
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                    , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_RESPONSE_STATUS, [
                        'type' => $type,
                        'status' => $answerDelayStatus,
                        'id' => $id
                    ]);
                // 图标显隐消息
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                    , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, [
                        'icon' => "/live/answer/{$typeName}_icon.png",
                        'hint' => '未开始',
                        'type' => $type,
                        'status' => $answerList ? 1 : 0,
                        'id' => 0
                    ]);

                // 排队用户
                foreach ($answerList as $uidItem => $idItem)
                {
                    if ($this->user['id'] != $uidItem)
                    {
                        $idItem = (int)$idItem;
                        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, $answerInfo['live_id'], $uidItem)
                            , LiveMessage::MSG_TYPE_POP_ANSWER_REFRESH, [
                                'target' => 'local',
                                'link' => "live_{$typeName}?id={$idItem}&live_record_id={$liveRecordId}&need_auth={$needAuth}",
                                'type' => $type,
                                'force_open' => 0
                            ]);
                    }
                }
                return show(config('code.success'), '操作成功', [
                    'title' => '',
                    'des' => '',
                ]);
            case 3:
                switch ($answerInfo['status'])
                {
                    case 7:
                    case 8:
                    case 9:
                        return show(config('code.error'), '解答申请已取消，操作失败～');
                    case 6:
                        return show(config('code.error'), '解答申请已完成，操作失败～');
                    case 5:
                        return show(config('code.error'), '正在解答中，操作失败～');
                    default:
                }

                // 付费
                if ($answerInfo['price'] > 0)
                {
                    $data = config('live_app.user_cancel_list');
                    $reason = $data[$reasonId]['name'] ?? '';
                    if (!$reason)
                    {
                        return show(config('code.error'), '取消原因异常，操作失败～');
                    }
                    //  更新订单信息 并退款
                    $res = $liveAnswerModel->refundAnswerOrder(['id' => $answerInfo['id'], 'order_num' => $answerInfo['order_num'], 'status' => $answerInfo['status'], 'uid' => $answerInfo['uid'],], $liveRecordId, 2, $reason);
                    if ($res === false)
                    {
                        return show(config('code.error'), '退款失败');
                    }
                    $payType = 2;//付费
                    if ($answerInfo['status'] === 1)
                    {   // 待支付订单    删除 准备 申请的信息 并且删除占位信息
                        $liveAnswerModel->delUserRequestAnswerPrepareInfo($answerInfo['live_id'], $liveRecordId, $this->user['id']);
                        // 释放占位
                        $liveAnswerModel->delAnswerPrepareUser($answerInfo['live_id'], $this->user['id']);
                    }
                } else
                { //免费
                    $reason = '手动取消';
                    // 更新解答状态
                    $liveAnswerModel->updateAnswerRequest([
                        'id' => $id,
                        'status' => 8,
                        'uid' => $this->user['id'],
                        'live_id' => $answerInfo['live_id'],
                        'live_record_id' => $liveRecordId,
                        'cancel_reason' => $reason,
                        'cancel' => $this->request->time(),
                        'answer_end_rid' => $liveRecordId
                    ]);
                    $payType = 1;//免费
                }
                //  当前操作的 申请问题 为当前正在解答的 申请
                $nowAnswerData = $liveAnswerModel->getNowAnswerDataByCache($liveRecordId);
                $isNow = false;
                if ($nowAnswerData && $id === (int)$nowAnswerData['id'])
                {   // 删除当前解答信息
                    $isNow = true;
                    $liveAnswerModel->delNowAnswerDataByCache($liveRecordId);
                }
                // 删除当前申请列表
                $liveAnswerModel->delRequestAnswerUserList($answerInfo['live_id'], $liveRecordId, $payType, (int)$answerInfo['uid']);
                // 加入 取消 列表
                if ($payType === 2 && $answerInfo['status'] !== 1)
                {   // 未支付订单除外
                    $liveAnswerModel->addResAnswerUserList($liveRecordId, 2, [$answerInfo['id'] => $answerInfo['id']]);
                }

                $answerList = $liveAnswerModel->getRequestAnswerUserList((int)$answerInfo['live_id'], $liveRecordId, $payType);
                //  ws 消息
                foreach ($answerList as $uid => $reqId)
                {
                    // 向直播间 申请用户 发送消息 发送更新详情消息
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_UID, $answerInfo['live_id'], $uid)
                        , LiveMessage::MSG_TYPE_POP_ANSWER_REFRESH, [
                            'target' => 'local',
                            'link' => "live_{$typeName}?id={$reqId}&live_record_id={$liveRecordId}&need_auth={$needAuth}",
                            'type' => $type,
                            'force_open' => 0
                        ]);
                }
                if (!$answerList)
                {
                    // 图标显隐消息
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                        , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, [
                            'icon' => "/live/answer/{$typeName}_icon.png",
                            'hint' => '未开始',
                            'type' => $type,
                            'status' => 0,
                            'id' => 0
                        ]);
                }

                if ($isNow)
                {
                    // 图标显隐消息
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                        , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, [
                            'icon' => "/live/answer/{$typeName}_icon.png",
                            'hint' => '未开始',
                            'type' => $type,
                            'status' => 1,
                            'id' => 0
                        ]);

                    // 向管理员 发送消息
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                        , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_RESPONSE_STATUS, [
                            'type' => $type,
                            'status' => 5,
                            'id' => $id
                        ]);
                }

                //  直播取消订单成功 LiveQuestionCancle 打点
                SensorsData::track($answerInfo['uid'], true, 'LiveQuestionCancle', [
                    'hoster_name' => $liveInfo['name'],    // 主播名称
                    'live_id' => $answerInfo['live_id'],    // 直播间ID
                    'live_record_id' => $liveRecordId,  // 直播记录ID
                    'price' => $answerInfo['price'] * 1,   //  价格
                    'cancle_reason' => $reason,
                    'question_type' => $answerName,   // 解答类型
                    'question' => $answerInfo['question'] ?? '',    // 问题的具体内容
                    'description' => $answerInfo['question_des'] ?? '无', // 问题的描述
                ]);

                return show(config('code.success'), '请求成功', [
                    'title' => '取消成功',
                    'des' => $answerInfo['price'] > 0 ? $answerInfo['status'] === 1 ? '订单已取消成功，可以重新申请～' : '订单支付资金会原路返还，请注意查收～' : '已成功取消申请',
                ]);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 骰子解答申请
     */
    public function requestDiceAnswer()
    {
        $liveRecordId = input('live_record_id/d', 0);
        $historyId = input('history_id/d', 0);
        $liveAnswerModel = new LiveAnswerDiceRecord();
        if (!$historyId)
        {
            return show(config('code.error'), '骰子异常，申请解答失败');
        }

        $diceInfo = (new Divination())->getDetail(['id' => $historyId]);
        if (!$diceInfo || (int)$diceInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '骰子异常，申请解答失败');
        }

        $liveRecordingInfo = new LiveRecordingInfo();
        $liveRecordInfo = $liveRecordingInfo->getInfoById($liveRecordId);
        // 获取当前 申请连麦信息
        $liveAnchorInfoModel = new LiveAnchorInfo();
        $resConfig = $liveAnchorInfoModel->getAnswerConfig($liveRecordInfo['live_id'], $liveRecordId, 'dice');

        if ((int)$resConfig['switch'] !== 1)
        {
            return show(config('code.error'), '主播未开启骰子解答');
        }
        $resConfig['type'] = (int)$resConfig['type'];
        $userGroupName = '所有人';
        if ($resConfig['type'] === 1)
        {   // 免费情况
            $resConfig['people_auth'] = (int)$resConfig['people_auth'];
            if ($resConfig['people_auth'] === 2)
            {
                $userGroupName = '下单用户';
                // 下单权限验证  是否在本场直播中下单
                $orderUids = (new LiveOrderData())->getLiveRecordOrderUid($liveRecordId);
                if (!$orderUids || !in_array($this->user['id'], $orderUids, false))
                {   // 下单了的用户
                    return show(config('code.error'), '主播设置了权限，请稍后再试～');
                }
            } elseif ($resConfig['people_auth'] === 3)
            {
                $userGroupName = '会员用户';
                $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
                if ($vipLevel < 1)
                {   // 不是VIP 则返回
                    return show(config('code.error'), '主播设置了权限，请稍后再试～');
                }
            }
        }

        // 获取申请的所有人
        $answerList = $liveAnswerModel->getRequestAnswerUserList($liveRecordInfo['live_id'], $liveRecordId, $resConfig['type']);
        // 判断申请人数是否已满
        if ($answerList)
        {
            $uids = array_keys($answerList);
            if (in_array($this->user['id'], $uids, false))
            {   // 已经申请过了  且 是申请成功
                return show(config('code.error'), '已经提交过申请了，不能再次申请～');
            }
        }
        $requestAnswerNum = count($answerList);    // 申请解答用户
        $isRequest = false;
        if ($resConfig['type'] === 2)
        {   // 付费
            // 当前有待支付订单 不允许再次申请
            $reqInfo = $liveAnswerModel->getUserRequestAnswerPrepareInfo($liveRecordInfo['live_id'], $liveRecordId, $this->user['id']);
            if ($reqInfo && (int)$reqInfo['status'] === 1)
            {
                return show(config('code.error'), '已经提交过申请了，不能再次申请～');
            }

            $prepareUser = $liveAnswerModel->getAnswerPrepareUser($liveRecordInfo['live_id']);
            if (in_array($this->user['id'], $prepareUser, false))
            {   //  已经占过位置
                $isRequest = true;
            } else
            {
                $requestAnswerNum = $requestAnswerNum + count($prepareUser);    // 加上 申请中用户
            }
        }

        if (!$isRequest && $requestAnswerNum >= $resConfig['max_people_num'])
        {
            return show(config('code.error'), '当前申请人数已满，请稍后再试～');
        }

        // 判断 骰子
        $answerInfo = [
            'uid' => (int)$this->user['id'],
            'live_id' => (int)$liveRecordInfo['live_id'],
            'live_record_id' => (int)$liveRecordId,
            'history_id' => $historyId,
            'price' => $resConfig['type'] == 2 ? $resConfig['price'] : 0,
        ];

        if ($resConfig['type'] === 2)
        {   // 付费
            $answerInfo['status'] = 0;
            $answerInfo['sign'] = uniqid();
            $liveAnswerModel->setUserRequestAnswerPrepareInfo($answerInfo['live_id'], $liveRecordId, $answerInfo['uid'], $answerInfo);
            // 占位
            $liveAnswerModel->addAnswerPrepareUser($answerInfo['live_id'], $answerInfo['uid']);
            // 释放占位 延迟队列 =>未生成订单 则释放 已生成订单则不释放
            Util::queuePush('live_answer_down_order_timeout_check', [
                'sign' => $answerInfo['sign'],
                'live_id' => $answerInfo['live_id'],
                'live_record_id' => $answerInfo['live_record_id'],
                'uid' => $answerInfo['uid'],
                'type' => 2
            ], 120);

            $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);

            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache((int)$answerInfo['uid']);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $coinPwdStatus = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码

            //  直播解答问题提交成功 LiveQuestionAdd 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionAdd', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'price' => $resConfig['price'],   //  价格
                'users_group' => '无',
                'question_type' => '骰子',   // 解答类型
                'question' => $diceInfo['question'] ?? '',    // 问题的具体内容
                'description' => '无', // 问题的描述
            ]);

            return show(config('code.success'), '请求成功', [
                'live_name' => $liveInfo['name'],
                'good_img' => '/live/answer/dice_icon2.png',
                'good_name' => '直播骰子解答',
                'price' => $resConfig['price'],
                'coin' => $coinNum,
                'is_set_password' => $coinPwdStatus,
            ]);
        } else
        {   // 免费
            $answerInfo['question'] = $diceInfo['question'] ?? '';
            $id = $liveAnswerModel->addAnswerRequest($answerInfo);

            $nowData = $liveAnswerModel->getNowAnswerDataByCache($liveRecordId);
            if ($nowData && (int)$nowData['status'] === 5)
            {
                $name = $nowData['nickname'];
                $avatar = $nowData['avatar'];
            }
            $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);
            //  直播解答问题提交成功 LiveQuestionAdd 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionAdd', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'price' => 0,   //  价格
                'users_group' => $userGroupName,
                'question_type' => '骰子',   // 解答类型
                'question' => $diceInfo['question'] ?? '',    // 问题的具体内容
                'description' => '无', // 问题的描述
            ]);
            //  直播解答申请成功    LiveQuestionApplySuccess    打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionApplySuccess', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'is_synastry' => false, // 是否合盘
                'question_type' => '骰子',   // 解答类型
                'price' => 0,   //  价格
                'question' => $diceInfo['question'] ?? '',    // 问题的具体内容
                'description' => '无', // 问题的描述
            ]);

            if ($nowData)
            {
                $liveWsData = [
                    'icon' => "/live/answer/dice_icon.png",
                    'hint' => (int)$nowData['status'] === 5 ? '解答中' : '待响应',
                    'type' => 2,
                    'status' => 1,
                    'id' => $id
                ];
            } else
            {
                $liveWsData = [
                    'icon' => "/live/answer/dice_icon.png",
                    'hint' => '未开始',
                    'type' => 2,
                    'status' => 1,
                    'id' => 0
                ];
            }
            // 图标显隐消息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, $liveWsData);

            return show(config('code.success'), '请求成功', [
                'id' => $id,
                'status' => 12,
                'title' => '正在等待解答中…',
                'des' => '已将结果发送至主播',
                'name' => $name ?? '',
                'avatar' => $avatar ?? '',
                'wait_tips' => '当前' . ($requestAnswerNum + 1) . '人等待…',
                'question' => $diceInfo['question']
            ]);
        }
    }

    /**
     * 塔罗解答申请
     */
    public function requestTarotAnswer()
    {
        $liveRecordId = input('live_record_id/d', 0);
        $historyId = input('history_id/d', 0);
        $liveAnswerModel = new LiveAnswerTarotRecord();
        if (!$historyId)
        {
            return show(config('code.error'), '塔罗异常，申请解答失败');
        }
        $tarotInfo = (new ZlTarotRecords())->getInfoById($historyId);
        if (!$tarotInfo || (int)$tarotInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '塔罗异常，申请解答失败');
        }
        $liveRecordingInfo = new LiveRecordingInfo();
        $liveRecordInfo = $liveRecordingInfo->getInfoById($liveRecordId);
        // 获取当前 申请连麦信息
        $liveAnchorInfoModel = new LiveAnchorInfo();
        $resConfig = $liveAnchorInfoModel->getAnswerConfig($liveRecordInfo['live_id'], $liveRecordId, 'tarot');

        if ((int)$resConfig['switch'] !== 1)
        {
            return show(config('code.error'), '主播未开启塔罗解答');
        }
        $resConfig['type'] = (int)$resConfig['type'];
        $userGroupName = '所有人';
        if ($resConfig['type'] === 1)
        {   // 免费情况
            $resConfig['people_auth'] = (int)$resConfig['people_auth'];
            if ($resConfig['people_auth'] === 2)
            {
                $userGroupName = '下单用户';

                // 下单权限验证  是否在本场直播中下单
                $orderUids = (new LiveOrderData())->getLiveRecordOrderUid($liveRecordId);
                if (!$orderUids || !in_array($this->user['id'], $orderUids, false))
                {   // 下单了的用户
                    return show(config('code.error'), '主播设置了权限，请稍后再试～');
                }
            } elseif ($resConfig['people_auth'] === 3)
            {
                $userGroupName = '会员用户';

                $vipLevel = (new ZlUserVip())->getUserVipLevel($this->user['id']);
                if ($vipLevel < 1)
                {   // 不是VIP 则返回
                    return show(config('code.error'), '主播设置了权限，请稍后再试～');
                }
            }
        }

        // 获取申请的所有人
        $answerList = $liveAnswerModel->getRequestAnswerUserList($liveRecordInfo['live_id'], $liveRecordId, $resConfig['type']);
        // 判断申请人数是否已满
        if ($answerList)
        {
            $uids = array_keys($answerList);
            if (in_array($this->user['id'], $uids, false))
            {   // 已经申请过了  且 是申请成功
                return show(config('code.error'), '已经提交过申请了，不能再次申请～');
            }
        }
        $requestAnswerNum = count($answerList);    // 申请解答用户
        $isRequest = false;
        if ($resConfig['type'] === 2)
        {   // 付费
            // 当前有待支付订单 不允许再次申请
            $reqInfo = $liveAnswerModel->getUserRequestAnswerPrepareInfo($liveRecordInfo['live_id'], $liveRecordId, $this->user['id']);
            if ($reqInfo && (int)$reqInfo['status'] === 1)
            {
                return show(config('code.error'), '已经提交过申请了，不能再次申请～');
            }

            $prepareUser = $liveAnswerModel->getAnswerPrepareUser($liveRecordInfo['live_id']);
            if (in_array($this->user['id'], $prepareUser, false))
            {   //  已经占过位置
                $isRequest = true;
            } else
            {
                $requestAnswerNum = $requestAnswerNum + count($prepareUser);    // 加上 申请中用户
            }
        }

        if (!$isRequest && $requestAnswerNum >= $resConfig['max_people_num'])
        {
            return show(config('code.error'), '当前申请人数已满，请稍后再试～');
        }

        // 判断 塔罗
        $answerInfo = [
            'uid' => (int)$this->user['id'],
            'live_id' => (int)$liveRecordInfo['live_id'],
            'live_record_id' => (int)$liveRecordId,
            'history_id' => $historyId,
            'price' => $resConfig['type'] == 2 ? $resConfig['price'] : 0,
        ];

        if ($resConfig['type'] === 2)
        {   // 付费
            $answerInfo['status'] = 0;
            $answerInfo['sign'] = uniqid();
            $liveAnswerModel->setUserRequestAnswerPrepareInfo($answerInfo['live_id'], $liveRecordId, $answerInfo['uid'], $answerInfo);
            // 占位
            $liveAnswerModel->addAnswerPrepareUser($answerInfo['live_id'], $answerInfo['uid']);
            // 释放占位 延迟队列 =>未生成订单 则释放 已生成订单则不释放
            Util::queuePush('live_answer_down_order_timeout_check', [
                'sign' => $answerInfo['sign'],
                'live_id' => $answerInfo['live_id'],
                'live_record_id' => $answerInfo['live_record_id'],
                'uid' => $answerInfo['uid'],
                'type' => 3
            ], 120);

            $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);

            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache((int)$answerInfo['uid']);  // 账户信息
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $coinPwdStatus = (isset($user_coin['password']) && $user_coin['password']) ? 1 : 0;  // 是否设置了支付密码

            //  直播解答问题提交成功 LiveQuestionAdd 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionAdd', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'price' => $resConfig['price'],   //  价格
                'users_group' => '无',
                'question_type' => '塔罗',   // 解答类型
                'question' => $tarotInfo['question'] ?? '',    // 问题的具体内容
                'description' => '无', // 问题的描述
            ]);
            return show(config('code.success'), '请求成功', [
                'live_name' => $liveInfo['name'],
                'good_img' => '/live/answer/tarot_icon2.png',
                'good_name' => '直播塔罗解答',
                'price' => $resConfig['price'],
                'coin' => $coinNum,
                'is_set_password' => $coinPwdStatus,
            ]);
        } else
        {   // 免费
            $answerInfo['question'] = $tarotInfo['question'] ?? '';
            $id = $liveAnswerModel->addAnswerRequest($answerInfo);

            $nowData = $liveAnswerModel->getNowAnswerDataByCache($liveRecordId);
            if ($nowData && (int)$nowData['status'] === 5)
            {
                $name = $nowData['nickname'];
                $avatar = $nowData['avatar'];
            }

            $liveInfo = (new LiveAnchorInfo())->getInfoById($answerInfo['live_id'], ['name']);
            //  直播解答问题提交成功 LiveQuestionAdd 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionAdd', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'price' => 0,   //  价格
                'users_group' => $userGroupName,
                'question_type' => '塔罗',   // 解答类型
                'question' => $tarotInfo['question'] ?? '',    // 问题的具体内容
                'description' => '无', // 问题的描述
            ]);
            //  直播解答申请成功    LiveQuestionApplySuccess    打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionApplySuccess', [
                'hoster_name' => $liveInfo['name'],    // 主播名称
                'live_id' => $answerInfo['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'is_synastry' => false, // 是否合盘
                'question_type' => '塔罗',   // 解答类型
                'price' => 0,   //  价格
                'question' => $tarotInfo['question'] ?? '',    // 问题的具体内容
                'description' => '无', // 问题的描述
            ]);

            if ($nowData)
            {
                $liveWsData = [
                    'icon' => "/live/answer/tarot_icon.png",
                    'hint' => (int)$nowData['status'] === 5 ? '解答中' : '待响应',
                    'type' => 3,
                    'status' => 1,
                    'id' => $id
                ];
            } else
            {
                $liveWsData = [
                    'icon' => "/live/answer/tarot_icon.png",
                    'hint' => '未开始',
                    'type' => 3,
                    'status' => 1,
                    'id' => 0
                ];
            }
            // 图标显隐消息
            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_LIVER, $answerInfo['live_id'], $answerInfo['live_id'])
                , LiveMessage::MSG_TYPE_POP_LIVE_ANSWER_ICON, $liveWsData);

            return show(config('code.success'), '请求成功', [
                'id' => $id,
                'status' => 12,
                'title' => '正在等待解答中…',
                'des' => '已将结果发送至主播',
                'name' => $name ?? '',
                'avatar' => $avatar ?? '',
                'wait_tips' => '当前' . ($requestAnswerNum + 1) . '人等待…',
                'question' => $tarotInfo['question']
            ]);
        }
    }

    /**
     * 获取打赏列表
     * @throws \Exception
     */
    public function rewardList()
    {
        $rewardList = config('live_app.reward_list');
        $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);  // 账户信息
        $hasCoinPwd = $user_coin['password'] ? 1 : 0;
        $data = [
            'coin_list' => array_values($rewardList),
            'user_coin' => (int)$user_coin['balance'],
            'has_coin_pwd' => $hasCoinPwd ?? 0,
        ];
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 打赏解答
     * @return Json
     * @throws \Exception]
     */
    public function rewardAnswer()
    {
        $coin_id = input('coin_id/d', 0);
        $id = input('id/d', 0); //解答申请id
        $type = input('type/d', 0);// 1=>直播间看盘，2=>直播间骰子，3=>直播间塔罗
        $password = input('password', '');//准币密码
        $liveRecordId = input('live_record_id/d', 0);//直播记录ID

        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常');
        }

        $coinInfo = config('live_app.reward_list');
        if (!isset($coinInfo[$coin_id]))
        {
            return show(config('code.error'), '打赏金额异常');
        }
        //验证申请是否存在
        $answerModel = null;
        switch ($type)
        {
            case 1://看盘
                $orderType = 19;
                $answerModel = new LiveAnswerAstroRecord();
                $question_type = '看盘';
                break;
            case 2:// 骰子
                $orderType = 20;
                $answerModel = new LiveAnswerDiceRecord();
                $question_type = '骰子';
                break;
            case 3:// 塔罗
                $orderType = 21;
                $answerModel = new LiveAnswerTarotRecord();
                $question_type = '塔罗';
                break;
        }

        $orderInfo = OrdersLib::createOrderId($orderType ?? 0);

        $history = $answerModel->getInfoById($id);
        if (!$history && (int)$history['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '解答不存在');
        }

        $liveRecordInfo = (new LiveRecordingInfo())->getInfoById($liveRecordId, ['live_id']);
        if (!$liveRecordInfo)
        {
            return show(config('code.error'), '直播不存在');
        }
        $anchor = (new LiveAnchorInfo())->getInfoById($liveRecordInfo['live_id'], ['name', 'avatar', 'live_id']);
        $anchor['live_record_id'] = $liveRecordId;
        //验证准币密码
        $accountRecordId = OrdersLib::checkCoinPayInfo(['total_amount' => $coinInfo[$coin_id]['coin'] / 10, 'uid' => $this->user['id'], 'order_id' => $orderInfo['order_id'], 'order_type' => $orderType ?? 0, 'gid' => $id], $password, 5, json_encode(['live_info' => $anchor], true));
        if ($accountRecordId)
        {
            //准币余额修改
            (new ZhunleUserAccount())->updateCoinInfo($this->user['id'], 5, ['id' => $accountRecordId, 'order_id' => $orderInfo['order_id']], $coinInfo[$coin_id]['coin'], 4);

            //添加打赏记录
            $data = [
                'uid' => $this->user['id'],
                'type' => $type,
                'answer_id' => $id,
                'live_record_id' => $liveRecordId,
                'coin' => $coinInfo[$coin_id]['coin'],
                'reason' => $coinInfo[$coin_id]['des'],
                'create_time' => time()
            ];
            (new LiveAnswerReward())->saveData($data);
            //更新解答打赏状态
            $answerModel->updateAnswerRequest(['id' => $id, 'reward_status' => 1]);

            CharLiveMessage::sendMsg(CharLiveMessage::who(CharLiveMessage::WHO_TYPE_APP_USER, $liveRecordInfo['live_id'], $liveRecordInfo['live_id']), CharLiveMessage::MSG_TYPE_POP_HEADER, [
                'title' => "{$this->user['nickname']} 打赏了主播，夸赞主播：{$coinInfo[$coin_id]['des']}",
                'target' => 'local',
                'link' => '',
                'continue_second' => 8,
            ]);

            CharLiveMessage::sendMsg(CharLiveMessage::who(CharLiveMessage::WHO_TYPE_LIVER, $liveRecordInfo['live_id'], $liveRecordInfo['live_id']), CharLiveMessage::MSG_TYPE_POP_HEADER, [
                'title' => "{$this->user['nickname']} 打赏了你：{$coinInfo[$coin_id]['coin']}准币 {$coinInfo[$coin_id]['des']}",
                'target' => 'local',
                'link' => '',
                'continue_second' => 8,
            ]);

            CharLiveMessage::sendMsg(CharLiveMessage::who(CharLiveMessage::WHO_TYPE_LIVER, $liveRecordInfo['live_id'], $liveRecordInfo['live_id']), CharLiveMessage::MSG_TYPE_POP_MSG_LIVER_ORDER, [
                'msg_info' => [
                    'color' => '#FFB500',
                    'content' => "{$this->user['nickname']} 打赏了你：{$coinInfo[$coin_id]['coin']}准币 {$coinInfo[$coin_id]['des']}",
                    'id' => 0
                ],
                'user_info' => null
            ]);

            //  直播解答打赏成功 LiveQuestionReward 打点
            SensorsData::track($this->user['id'], true, 'LiveQuestionReward', [
                'hoster_name' => $anchor['name'],    // 主播名称
                'live_id' => $anchor['live_id'],    // 直播间ID
                'live_record_id' => $liveRecordId,  // 直播记录ID
                'reward_amount' => $coinInfo[$coin_id]['coin'],   //  价格
                'question_type' => $question_type ?? '',   // 解答类型
                'question' => $history['question'] ?? '',    // 问题的具体内容
                'description' => $history['question_des'] ?? '无', // 问题的描述
            ]);
            return show(config('code.success'), '打赏成功');
        }
        return show(config('code.error'), '打赏失败');
    }

    /**
     * 评价解答
     * @return Json
     * @throws \Exception
     */
    public function commentAnswer()
    {
        $star = input('star/d', 0);//评级
        $id = input('id/d', 0); //解答申请id
        $type = input('type/d', 0);// 1=>直播间看盘，2=>直播间骰子，3=>直播间塔罗
        $reason = trim(input('reason/s', ''));
        $liveRecordId = input('live_record_id/d', 0);

        if (!$liveRecordId)
        {
            return show(config('code.error'), '请求异常');
        }
        //评级处理
        if ($star <= 0)
        {
            $star = 1;
        } elseif ($star > 5)
        {
            $star = 5;
        }
        if ($star < 4 && !$reason)
        {
            return show(config('code.error'), '三星以下必须添加原因');
        }
        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常');
        }
        //验证申请是否存在
        $answerModel = null;
        switch ($type)
        {
            case 1://看盘
                $questionTypeName = '看盘';
                $answerModel = new LiveAnswerAstroRecord();
                break;
            case 2:// 骰子
                $questionTypeName = '骰子';
                $answerModel = new LiveAnswerDiceRecord();
                break;
            case 3:// 塔罗
                $questionTypeName = '塔罗';
                $answerModel = new LiveAnswerTarotRecord();
                break;
        }
        $history = $answerModel->getInfoById($id);
        if (!$history || (int)$history['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '解答不存在');
        }
        //添加评价记录
        $data = [
            'uid' => $this->user['id'],
            'type' => $type,
            'answer_id' => $id,
            'live_record_id' => $history['live_record_id'],
            'star' => $star,
            'reason' => $reason,
            'create_time' => time()
        ];
        (new LiveAnswerScore())->saveData($data);

        $liveInfo = (new LiveAnchorInfo())->getInfoById($history['live_id'], ['name']);

        //  直播解答评价 LiveQuestionComment 打点
        SensorsData::track($this->user['id'], true, 'LiveQuestionComment', [
            'hoster_name' => $liveInfo['name'],    // 主播名称
            'live_id' => (int)$history['live_id'],    // 直播间ID
            'live_record_id' => $history['live_record_id'],  // 直播记录ID
            'question_type' => $questionTypeName ?? '未知',   // 解答类型
            'question' => $history['question'] ?? '',    // 问题的具体内容
            'description' => $type === 1 ? $history['question_des'] ?? '' : '无', // 问题的描述
            'estimate_level' => $star,
        ]);

        //更新解答评价状态
        $answerModel->updateAnswerRequest(['id' => $id, 'evaluate_status' => 1]);
        return show(config('code.success'), '评价成功');
    }

    /**
     * 解答详情
     * @throws \Exception
     */
    public function answerDetailInfo()
    {
        $id = input('id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);//直播记录id
        $type = input('type/d', 0);//  1=>直播间看盘，2=>直播间骰子，3=>直播间塔罗
        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常');
        }
        $answerModel = null;
        switch ($type)
        {
            case 1://看盘
                $answerModel = new LiveAnswerAstroRecord();
                break;
            case 2:// 骰子
                $answerModel = new LiveAnswerDiceRecord();
                break;
            case 3:// 塔罗
                $answerModel = new LiveAnswerTarotRecord();
                break;
        }
        $data = $answerModel->getAnswerStatusDetail($id, $this->user['id'], $liveRecordId);
        if (isset($data['code']))
        {
            return show($data['code'], $data['title']);
        }
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 获取解答历史详情
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function answerOrderDetail()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);

        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '解答类型异常');
        }
        $answerModel = null;
        switch ($type)
        {
            case 1:
                $answerModel = new LiveAnswerAstroRecord();
                break;
            case 2:
                $answerModel = new LiveAnswerDiceRecord();
                break;
            case 3:
                $answerModel = new LiveAnswerTarotRecord();
                break;
        }
        $history = $answerModel->getInfoById($id);
        if (!$history || $history['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '解答不存在');
        }

        $data = [];
        //状态  1=>待支付 2=>等待解答｜排队中  3=>待响应 4=>未响应 5=>解答中 6=>解答完成 7=>订单关闭取消(待支付状态取消) 8=>用户主动取消 9=>主播取消 10=>未响应3次后取消（支付成功后）
        switch ($history['status'])
        {
            case 1:
                $currentIndex = 0;
                break;
            case 2:
                $currentIndex = 1;
                break;
            case 3:
            case 4:
                $currentIndex = 2;
                break;
            case 5:
                $currentIndex = 3;
                break;
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
                $currentIndex = 4;
                break;
        }
        $data['common_progress'] = [
            'current_index' => $currentIndex,
            'list' => ['申请成功', '等待解答', '用户响应', '解答中', '完成']
        ];
        $data['common_question_list'] = [
            [
                'title' => '我的问题',
                'desc' => $history['question']
            ]
        ];
        switch ($type)
        {
            case 1:
                $recodeList = [];
                $recode = json_decode($history['extend'], true);
                if (isset($recode['recode1']) && $recode['recode1'])
                {
                    $recodeList[] = [
                        'id' => $recode['recode1']['id'],
                        'name' => $recode['recode1']['name'],
                        'type' => $recode['recode1']['type'] == 1 ? 1 : 2,
                        'age' => '年龄' . birthday($recode['recode1']['year'] . '-' . $recode['recode1']['month'] . '-' . $recode['recode1']['day']),
                        'comments' => $recode['recode1']['comments']
                    ];
                }
                if (isset($recode['recode2']) && $recode['recode2'])
                {
                    $recodeList[] = [
                        'id' => $recode['recode2']['id'],
                        'name' => $recode['recode2']['name'],
                        'type' => $recode['recode2']['type'] == 1 ? 1 : 2,
                        'age' => '年龄' . birthday($recode['recode2']['year'] . '-' . $recode['recode2']['month'] . '-' . $recode['recode2']['day']),
                        'comments' => $recode['recode2']['comments']
                    ];
                }
                $data['astro_data'] = [
                    'title' => '档案',
                    'recode_list' => $recodeList
                ];
                $data['common_question_list'][] = [
                    'title' => '我的问题描述',
                    'desc' => $history['question_des']
                ];
                break;
            case 2:
                $diceInfo = (new Divination())->getDetail(['id' => $history['history_id']]);
                $data['dice_data'] = [
                    'title' => '结果',
                    'dice' => [
                        'planet' => $diceInfo['planet'],
                        'sign' => $diceInfo['sign'],
                        'house' => $diceInfo['house'],
                    ]
                ];
                break;
            case 3:
                $tarotRecordModel = new ZlTarotRecords();
                $tarot = $tarotRecordModel->getInfoById($history['history_id']);
                $detail = $tarotRecordModel->getDetails($tarot);
                $data['tarot_data'] = [
                    'title' => '结果',
                    'tarot_cards' => $detail['tarot_cards']
                ];
                break;
        }
        return show(config('code.success'), '获取成功', $data);
    }
}
